package com.itheima.controller;

import com.itheima.pojo.Customer;
import com.itheima.service.CustomerService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

import java.util.List;

@Controller
@RequestMapping("/customer")
public class CustomerController {
    
    @Autowired
    private CustomerService customerService;
    
    /**
     * 显示客户列表页面
     */
    @GetMapping("/list")
    public String list(Model model) {
        List<Customer> customers = customerService.findAll();
        model.addAttribute("customers", customers);
        return "customer/list";
    }
    
    /**
     * 显示客户详情页面
     */
    @GetMapping("/detail/{id}")
    public String detail(@PathVariable("id") Integer id, Model model) {
        Customer customer = customerService.findById(id);
        model.addAttribute("customer", customer);
        return "customer/detail";
    }
    
    /**
     * 根据客户名称搜索
     */
    @GetMapping("/search")
    public String search(@RequestParam(value = "customerName", required = false) String customerName, Model model) {
        List<Customer> customers;
        if (customerName != null && !customerName.trim().isEmpty()) {
            customers = customerService.findByName(customerName);
        } else {
            customers = customerService.findAll();
        }
        model.addAttribute("customers", customers);
        model.addAttribute("customerName", customerName);
        return "customer/list";
    }
}
